package com.ebelter.nb.ui.activitys;



import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.products.nb.BondDevices;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.dialogs.TextTipDialog;
import com.ebelter.nb.R;
import com.ebelter.nb.model.dao.DbUtils;
import com.ebelter.nb.model.http.request.NbNetUtils;
import com.ebelter.nb.model.http.response.BandDeviceListResponse;
import com.ebelter.nb.model.http.response.NbBandDeviceResponse;
import com.ebelter.nb.ui.view.Tip1Dialog;
import com.ebelter.nb.utils.NbUtitls;
import com.znq.zbarcode.CaptureActivity;


import java.util.List;

import zxing.android.CaptureActivity2;

public class AddDeviceActivity extends NBBaseActivity implements View.OnClickListener {
    public static final String TAG = "AddDeviceActivity";
    //public static String isAutoGoCupActivity = "isAutoGoCupActivity";
    public static final int requestCode = 109;

    private ImageView top_left_iv;

    private RelativeLayout adddevice_bpm_rl;
    private View adddevice_bpm_rl_buttomV;
    private RelativeLayout adddevice_scale_rl;
    private View adddevice_scale_rl_buttomV;


    private ProductStyle currentBondProductStyle = ProductStyle.NO;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_adddevice;
    }

    @Override
    protected void initView() {
        super.initView();
        FV();
        setListener();
    }

    private static final int GO2RESULTSHOW = 10;

    @Override
    protected void initData() {

        if (NetUtils.available()){
            getBandDeviceFromNet(NbUtitls.getLoginUserId(),0,0);
        }else {
            disNewestViews();
        }


    }

    private void getBandDeviceFromNet(final String user_id, final int cmd,final int type) {

        LogUtils.i(TAG,"----getBandDeviceFromNet--");

        NbNetUtils.getInstance().getUserBandList(this, user_id, new HttpResponse<BandDeviceListResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BandDeviceListResponse bandDeviceListResponse, String s) {
                LogUtils.i("getUserBandList",TAG+"----getUserBandList--"+s);
                LogUtils.i(TAG,"----getUserBandList--"+s);
                DbUtils.deleteTable(BondDevices.class);
                if (isRequestSuccess&&bandDeviceListResponse!=null&&bandDeviceListResponse.status==0){

                    if (bandDeviceListResponse.data!=null){
                        for (int i=0;i<bandDeviceListResponse.data.size();i++){
                            BandDeviceListResponse.DataBean dataBean = bandDeviceListResponse.data.get(i);

                            BondDevices bondDevices = new BondDevices();
                            bondDevices.user_id = user_id;
                            bondDevices.type = dataBean.type;
                            bondDevices._id = dataBean.id;
                            bondDevices.sn_number = dataBean.sn_number;
                            bondDevices.device_id = dataBean.device_id;//保存的IMEI
                            bondDevices.create_time = dataBean.create_time;
                            bondDevices.save();
                        }
                    }

                    disNewestViews();

                    if (cmd==GO2RESULTSHOW){
                        openResultShow(type);
                    }
                }
            }
        });

    }

    private void openResultShow(int type) {
        //跳转到绑定成功界面
        Intent intent = new Intent(AddDeviceActivity.this,AddDeviceResultActivity.class);
        intent.putExtra(AddDeviceResultActivity.ProductStyles,type==0?ProductStyle.BPM:ProductStyle.SCALE);
        startActivity(intent);
    }


    private void disNewestViews(){
        LogUtils.i(TAG,"----disNewestViews--");
        ViewUtils.displayView(adddevice_bpm_rl);
        ViewUtils.displayView(adddevice_bpm_rl_buttomV);
        ViewUtils.displayView(adddevice_scale_rl);
        ViewUtils.displayView(adddevice_scale_rl_buttomV);

        List<BondDevices> list = NbUtitls.queryBondedDevices();
        if (list==null||list.size()==0){
          //说明没有绑定
        }else{
            int bondeds=0;
            for (BondDevices bond:list){
                if (bond==null) continue;
                if (bond.type==1){//1为体脂秤
                    ViewUtils.goneView(adddevice_scale_rl);
                    ViewUtils.goneView(adddevice_scale_rl_buttomV);
                    bondeds++;
                }else if (bond.type==0){//0为血压计
                    ViewUtils.goneView(adddevice_bpm_rl);
                    ViewUtils.goneView(adddevice_bpm_rl_buttomV);
                    bondeds++;
                }
            }

            if (bondeds>=2){
                LogUtils.i(TAG,"绑定的设备已经全部绑定-finish（）");
                ToastUtil.show("设备已经全部绑定");
                setResult(2);
                finish();
            }
        }

    }

    private void setListener() {
        top_left_iv.setOnClickListener(this);
        adddevice_bpm_rl.setOnClickListener(this);
        adddevice_scale_rl.setOnClickListener(this);
    }

    private void FV() {
        top_left_iv=findViewById(R.id.top_left_iv);
        TextView title_tv = findViewById(R.id.m_title_tv);
        TextView rightTitle_tv = findViewById(R.id.m_righttitle_tv);
        ViewUtils.setTextViewStr(title_tv,"添加新设备");
        ViewUtils.hideView(rightTitle_tv);
        adddevice_bpm_rl=findViewById(R.id.adddevice_bpm_rl);
        adddevice_scale_rl=findViewById(R.id.adddevice_scale_rl);
        adddevice_bpm_rl_buttomV=findViewById(R.id.adddevice_bpm_rl_buttomV);
        adddevice_scale_rl_buttomV=findViewById(R.id.adddevice_scale_rl_buttomV);
    }

    @Override
    public void onClick(View v) {
        int vid=v.getId();
        if (vid==R.id.top_left_iv){
            finish();
        }else if (vid==R.id.adddevice_bpm_rl){
            currentBondProductStyle=ProductStyle.BPM;

            openCaptureActivity(0);
        }else if (vid==R.id.adddevice_scale_rl){

            showTipDialog();

        }
    }

    //展示提示对话框
    private Tip1Dialog tip1Dialog;
    private void showTipDialog() {

        if (tip1Dialog==null){
            tip1Dialog=new Tip1Dialog(this,"图上所示体脂秤设备上的“网络图标”亮起即可绑定");
            tip1Dialog.setListener(new Tip1Dialog.ICancelOkBtListener() {
                @Override
                public void ok(Dialog dialogView) {
                    currentBondProductStyle=ProductStyle.SCALE;

                    openCaptureActivity(1);
                    tip1Dialog.dismiss();
                }
            });
        }
        tip1Dialog.show();




    }

    private void openCaptureActivity(int product){//0血压计 1体脂秤

        if (product==1){
            CaptureActivity.tip="把体脂秤的二维码放入框内即可自动扫描";
            Intent intent1 = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent1, 1001);
        }else {
            Intent intent = new Intent(this,
                    CaptureActivity2.class);
            startActivityForResult(intent, 1002);
        }

    }

    private static String getSn(String result){
        return result.substring(result.indexOf("?sn=")+4,result.length());
    }
    private static final String DECODED_CONTENT_KEY = "codedContent";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if((requestCode==1001||requestCode==1002) && resultCode== Activity.RESULT_OK) {
           // String result=data.getStringExtra(CaptureActivity.KEY_DATA);
            //返回的文本内容
            if(null==data) return;

            String result=null;
            if (requestCode==1002){
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
               // Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                result=content;

                //qrCoded.setText("解码结果： \n" + content);
               // qrCodeImage.setImageBitmap(bitmap);
            }else {
                Bundle b=data.getExtras();
                if(b!=null){
                    result= b.getString(CaptureActivity.EXTRA_STRING);
                }
            }







            LogUtils.i(TAG,"--------------二维码字符串:"+result);

            if (TextUtils.isEmpty(result)){
                ToastUtil.show("此二维码不符合产品");
            }else {

               // http://shangxun.belter.com.cn/download/index.html?sn=QT01SN00000051
                //移动 Y ，联通 L ，电信 D ,全网通 Q

                String sn = getSn(result);
                //http://shangxun.belter.com.cn/download/index.html?sn=QN01SN00000011

                if (!TextUtils.isEmpty(sn)){
                    String productStyle = sn.substring(1,4);
                    if (currentBondProductStyle==ProductStyle.BPM&&productStyle.startsWith("N01")){
                        bandDevices(sn,0);
                    }else if (currentBondProductStyle==ProductStyle.SCALE&&productStyle.startsWith("T01")){
                        bandDevices(sn,1);
                    }else {
                        ToastUtil.show("此二维码不符合产品");
                    }
                }




            }


        }else if (requestCode==AddDeviceResultActivity.AddDeviceResultActivity_Request&&resultCode==AddDeviceResultActivity.BDQT){
            //绑定其他
          //  openCaptureActivity();
            disNewestViews();
           getBandDeviceFromNet(NbUtitls.getLoginUserId(),0,0);
        }
    }





    //绑定二维码  type=0血压计 type=1体脂秤
    private void bandDevices(final String erweima, final int type) {
        final String loginUserId = NbUtitls.getLoginUserId();
        //startsWith("N01")
        NbNetUtils.getInstance().userBandDevice(this, erweima,loginUserId , type, new HttpResponse<NbBandDeviceResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, NbBandDeviceResponse nbBandDeviceResponse, String s) {

                LogUtils.i(TAG,"---bandDevices--"+s+"---"+nbBandDeviceResponse);

                if (isRequestSuccess&&nbBandDeviceResponse!=null&&nbBandDeviceResponse.status==0){
//                    //绑定成功
//                    BondDevices bondDevices = new BondDevices();
//                    bondDevices.user_id = loginUserId;
//                    bondDevices.type = type;
//
//                    if (nbBandDeviceResponse.getData()!=null&&!TextUtils.isEmpty(nbBandDeviceResponse.getData().device_id)){
//                        bondDevices.device_id = nbBandDeviceResponse.getData().device_id;
//                    }
//
//                    bondDevices.save();

                    ToastUtil.show("绑定成功");

               //     disNewestViews();

                    getBandDeviceFromNet(loginUserId,GO2RESULTSHOW,type);



                }else if (nbBandDeviceResponse!=null&&nbBandDeviceResponse.status==1){
                    //绑定失败
                    ToastUtil.show("SN号码未绑定IEMI");
                }else if (nbBandDeviceResponse!=null&&nbBandDeviceResponse.status==2){
                    //绑定失败
                    ToastUtil.show("你已经绑定过一台设备,请先解除绑定！");
                }else {
                    ToastUtil.show("绑定失败");
                }



            }
        });
    }
}
